package cn.jbooter.session.autoconfigure;

import java.io.IOException;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.boot.env.PropertySourcesLoader;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.core.io.support.ResourcePatternResolver;


/**
 * 初始化session自定义配置到environment中
 * 
 * @author HeJian
 */
public class RedisSessionPropertiesInitializer implements EnvironmentPostProcessor{
	private static final Logger logger = LoggerFactory.getLogger(RedisSessionPropertiesInitializer.class);
	
	/** 配置文件路径 **/
	private static final String location_properties="classpath:session-config/redis-session-config.yml";
	/** 配置文件的编码 **/
	private static final String PROPERTIES_FILE_ENCODING="UTF-8";

	@Override
	public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
		//解析配置文件资源
		ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		Resource[] resources = null;
		try {
			resources = resolver.getResources(location_properties);
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException("读取classpath:session-config/redis-session-config.yml出错,请检查文件是否存在!"+e.getMessage());
		}
		
		//将配置添加进environment
		for(Resource resource : resources) {
			PropertySourcesLoader propertiesLoader = new PropertySourcesLoader();
			try {
				PropertySource<?> ps = null;
				//解决读取properties配置文件中文乱码问题
				if(resource.getFilename().endsWith("."+"properties")) {
					EncodedResource rs = new EncodedResource(resource,PROPERTIES_FILE_ENCODING);
					Properties props = PropertiesLoaderUtils.loadProperties(rs);
					ps = new PropertiesPropertySource(resource.getDescription(), props);
				}else {
					ps = propertiesLoader.load(resource);
				}
				if(ps==null) continue;
				environment.getPropertySources().addFirst(ps);
			} catch (IOException e) {
				e.printStackTrace();
				logger.warn("load cust properties config file ["+resource.getFilename()+"] is failed ! cause : "+e.getMessage());
			}
		}
	}
	

}
